//
//  GBShortMessageViewController.m
//  PublicSentimentMonitorSystem
//
//  Created by 郭斌 on 15/11/23.
//  Copyright © 2015年 魏强. All rights reserved.
//

#import "GBShortMessageViewController.h"
#import "GBShortMessageTableView.h"
#import "UniversialTextfield.h"
#import "AFNetworking.h"
#import "SVProgressHUD.h"

@interface GBShortMessageViewController ()<UITextFieldDelegate>
{
    //11.23
    GBShortMessageTableView *shortmessageTableview; //短信列表
    UIView *inputView; //输入框背景view
    UniversialTextfield *inputTextfield; //输入框
    UIButton *sendBtn; //发送按钮
}
@end

@implementation GBShortMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    self.title = @"短信";
    self.view.backgroundColor = [UIColor whiteColor];
    
    //创建主界面
    [self createMainView];
    
    //创建输入框
    [self createInputField];
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(CalmDown)];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = NO;
    //将触摸事件添加到当前view
    [shortmessageTableview addGestureRecognizer:tapGestureRecognizer];
    // Do any additional setup after loading the view.
}

#pragma mark - 创建主界面
-(void)createMainView
{
    //创建短信界面
    shortmessageTableview = [[GBShortMessageTableView alloc] initWithFrame:CGRectMake(0, 4, screenW, screenH - 64)];
    //shortmessageTableview.delegate = self;
    //shortmessageTableview.dataSource =self;
    [self.view addSubview:shortmessageTableview];
}

#pragma mark - 创建输入框
-(void)createInputField
{
    inputView = [[UIView alloc] initWithFrame:CGRectMake(0, screenH - 154, screenW, 40)];
    inputView.backgroundColor = WQColor(238, 240, 242);
    
    inputTextfield = [[UniversialTextfield alloc] initWithFrame:CGRectMake(5, 5, screenW - 55, 30)];
    inputTextfield.placeholder = @"输入信息内容";
    inputTextfield.returnKeyType = UIReturnKeyDone;
    inputTextfield.clearButtonMode = UITextFieldViewModeAlways;
    inputTextfield.borderStyle = UITextBorderStyleRoundedRect;
    inputTextfield.delegate = self;
    
    sendBtn = [UIButton buttonWithType:0];
    sendBtn.frame = CGRectMake(screenW - 45, 5, 40, 30);
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    sendBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [sendBtn setTitleColor:WQColor(123, 123, 127) forState:UIControlStateNormal];
    sendBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [sendBtn addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:inputView];
    [inputView addSubview:inputTextfield];
    [inputView addSubview:sendBtn];
}

#pragma mark - 键盘坐标改变
-(void)keyboardWillChangeFrame:(NSNotification *)note
{
    NSDictionary *dict = note.userInfo;
    //动画持续的时间
    double duration = [dict[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //键盘的frame
    CGRect keyboardF = [dict[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    //开启动画
    [UIView animateWithDuration:duration animations:^{
        
        if(keyboardF.origin.y == screenH)
        {
            inputView.frame = CGRectMake(0, keyboardF.origin.y - 154, screenW, 40);
        }
        else
        {
            inputView.frame = CGRectMake(0, keyboardF.origin.y - 105, screenW, 40);
        }
    }];
}

#pragma mark - textfield代理
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //键盘下降
    [self CalmDown];
    return YES;
}

#pragma mark - 键盘下降
-(void)CalmDown
{
    if([inputTextfield isFirstResponder])
    {
        [inputTextfield resignFirstResponder];
    }
}

#pragma mark - 发送信息
-(void)sendMessage
{
    //if([inputTextfield isFirstResponder])
    //{
        if(inputTextfield.text.length == 0)
        {
            [SVProgressHUD showErrorWithStatus:@"输入不能为空" maskType:SVProgressHUDMaskTypeGradient];
            return;
        }
        //发送短信，请求url
        KDAccount *account = [KDAccountTool account];
        NSString *inputS = [NSString stringWithFormat:@"%@",inputTextfield.text];
        inputS = [inputS stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
        NSString *saveUrl = [NSString stringWithFormat:@"%@%@%@%@%@", ServerActionAddr, @"&method=reportShortMessage&token=",account.tokens,@"&message=",inputS];
        //NSLog(@"%@",saveUrl);
        //请求数据
        NSURLRequest *httpReq = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:saveUrl]];
        
        AFHTTPRequestOperation *reqOper = [[AFHTTPRequestOperation alloc] initWithRequest:httpReq];
        [reqOper setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *op,id success){
            NSHTTPURLResponse *response = [op response];
            NSInteger code = [response statusCode];
            if (code == 200)
            {
                NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[op responseData] options:NSJSONReadingMutableContainers error:nil];
                if([jsonDict[@"status"] isEqualToString:@"ok"])
                {
                    if([jsonDict[@"info"] intValue] == 1)
                    {
                        [SVProgressHUD showSuccessWithStatus:@"发送成功" maskType:SVProgressHUDMaskTypeGradient];
                        inputTextfield.text = nil;
                        //刷新列表
                        [shortmessageTableview lateeeee];
                    }
                    else if([jsonDict[@"info"] intValue] == 0)
                    {
                        [SVProgressHUD showErrorWithStatus:@"发送失败" maskType:SVProgressHUDMaskTypeGradient];
                    }
                }
                //账号在别处登录
                else if([jsonDict[@"status"] isEqualToString:@"notlogin"])
                {
                    [SVProgressHUD showSuccessWithStatus:@"该账号在别处登录" maskType:SVProgressHUDMaskTypeGradient];
                    
                    KDNewfeatureController *login = [[KDNewfeatureController alloc] init];
                    //跳转到登陆界面
                    //设置切换风格
                    login.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                    //2.切换控制器
                    [self presentViewController:login animated:YES completion:nil];
                }
                //保存失败
                else if ([jsonDict[@"status"] isEqualToString:@"err"])
                {
                    [SVProgressHUD showErrorWithStatus:@"发送失败" maskType:SVProgressHUDMaskTypeGradient];
                }
                //已存在
                else if ([jsonDict[@"status"] isEqualToString:@"ext"])
                {
                    [SVProgressHUD showErrorWithStatus:@"已存在" maskType:SVProgressHUDMaskTypeGradient];
                }
            }
        } failure:^(AFHTTPRequestOperation *op, NSError *error) {
            if (error)
            {
                //NSLog(@"req error %@",error);
                [SVProgressHUD showErrorWithStatus:@"发送失败" maskType:SVProgressHUDMaskTypeGradient];
            }
        }];
        [reqOper start];
        [inputTextfield resignFirstResponder];
    //}
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
